Set Featured Image Programmatically

This sets featured image programmatically

With AJAX… all you need is the image URL to be sent to your ajax file. It then copies the image to the uploads folder and sets it as the “featured image” for the post ID you ALSO sent up with the AJAX call.

function ee_set_featured_image() {



            $image           = $_POST["image"];
            $post_id         = $_POST["post_id"];
            
            update_post_meta($post_id, '_thumbnail_id', $image);
            
			$this_base = basename($image);
			$up_info   = wp_upload_dir();
			$this_path = $up_info['path']."/$this_base";
			file_put_contents($this_path, file_get_contents($image));
			
			
			
			
			
// $filename should be the path to a file in the upload directory.
$filename = $this_path;

// The ID of the post this attachment is for.
$parent_post_id = $post_id;

// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );

// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();

// Prepare an array of post data for the attachment.
$attachment = array(
	'guid'           => $wp_upload_dir['url'] . '/' . basename( $filename ), 
	'post_mime_type' => $filetype['type'],
	'post_title'     => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
	'post_content'   => '',
	'post_status'    => 'inherit'
);

// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );

// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );

// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

set_post_thumbnail( $parent_post_id, $attach_id );
			
			
			
			
			
	
			
			if ( $image ) {
			    $return['status'] = "featured set";
			} else {
			    $return['status'] = "failed";
			} 
		    
			echo json_encode($return);
            die(); 

}

add_action("wp_ajax_ee_set_featured_image", "ee_set_featured_image");


Comments